from utils.genuuid import uuid1
from contextvars import ContextVar
from datetime import datetime

from peewee import MySQLDatabase, _ConnectionState, Model, UUIDField, DateTimeField

db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None}
db_state = ContextVar("db_state", default=db_state_default.copy())


class PeeweeConnectionState(_ConnectionState):
    def __init__(self, **kwargs):
        super().__setattr__("_state", db_state)
        super().__init__(**kwargs)

    def __setattr__(self, name, value):
        self._state.get()[name] = value

    def __getattr__(self, name):
        return self._state.get()[name]


db = MySQLDatabase('guzhou', user='guzhou', password="Wkrh876a8rRMwyDC", host='62.234.69.225', port=3306)
db._state = PeeweeConnectionState()


class BaseModel(Model):
    id = UUIDField(default=uuid1, primary_key=True, verbose_name="UUID")
    create_at = DateTimeField(default=datetime.now, verbose_name="创建时间")
    update_at = DateTimeField(default=datetime.now, verbose_name="更新时间")
    delete_at = DateTimeField(default=None, verbose_name="删除时间")

    def save(self, *args, **kwargs):
        """覆写save方法, update_time字段自动更新, 实例对象需要在update成功之后调用save()"""
        if self._get_pk_value() is None:
            # this is a create operation, set the date_created field
            self.create_at = datetime.now().strftime(
                "%Y-%m-%d %H:%M:%S")
        self.update_at = datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S")
        return super(Model, self).save(*args, **kwargs)

    @classmethod
    def all(cls):
        return list(cls.select())

    @classmethod
    def page(cls, skip: int = 0, limit: int = 100):
        return list(cls.select().offset(skip).limit(limit))
